﻿using System.Collections.Generic;
using System.Linq;
using SverigesRadio.SverigesRadioApp.Business;
using SverigesRadio.SverigesRadioApp.Business.Model;
using Caliburn.Micro;

namespace SverigesRadio.SverigesRadioApp.WindowsPhoneApplication.ViewModels.Programs
{
   
    public class ProgramCategoriesViewModel : PropertyChangedBase,  IMainPagePivotViewModel
    {
        public const string TitleText_Programs = "Program A-Ö";
        public const string TitleText_ArchivedPrograms = "Arkiverade program";

        private IServiceCaller<ProgramCategories> categoryService;

        public ProgramCategoriesViewModel(MainPageViewModel parentViewModel)
        {
            ParentViewModel = parentViewModel;

            categoryService = parentViewModel.DataContext.GetProgramCategoriesServiceCaller();
            categoryService.OnServiceCallReceived += OnServiceCallReceived;

        }

        private List<ListItem<ProgramCategory>> programCategories;
        public List<ListItem<ProgramCategory>> ProgramCategories
        {
            get { return programCategories; }
            set
            {
                programCategories = value;
                NotifyOfPropertyChange(() => ProgramCategories);
            }
        }

        private ListItem<ProgramCategory> selectedProgramCategory;
        public ListItem<ProgramCategory> SelectedProgramCategory
        {
            get { return selectedProgramCategory; }
            set
            {
                selectedProgramCategory = value;

                string programCategoryId = null;

                if (value == null)
                    return;

                if (value.ItemData != null)
                    programCategoryId = value.ItemData.Id;

                ParentViewModel.NavigationService.UriFor<ProgramsPageViewModel>().WithParam(p => p.ProgramCategoryId, programCategoryId).WithParam
                    (p => p.CategoryTitleText, value.Title).Navigate();
            }
        }

        void OnServiceCallReceived(object sender, ServiceCallerEventArgs<ProgramCategories> e)
        {
            ParentViewModel.IsBusy = false;

            if (e.Error != null)
                throw e.Error;

            List<ListItem<ProgramCategory>> listItems = e.ServiceResult.Categories.Select(p => new ListItem<ProgramCategory>(p.Title, p)).ToList();
            listItems.Insert(0, new ListItem<ProgramCategory>(TitleText_ArchivedPrograms, null));
            listItems.Insert(0, new ListItem<ProgramCategory>(TitleText_Programs, null));

            ProgramCategories = listItems;

        }

        public MainPageViewModel ParentViewModel { get; private set; }

        public void Loaded()
        {
            ParentViewModel.IsBusy = true;

            categoryService.CallAsync(SverigesRadioServices.ProgramCategories);
        }


    }
}
